package ExperimentSix.Tensorflow;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TaskDistributor implements Runnable {
    private final Socket workerSocket;//worker的线程数Socket
    private final int taskCount;//任务的数量
    private final Master master;//master对象
//TaskDistributor方法
    public TaskDistributor(Socket workerSocket, int taskCount, Master master) {
        this.workerSocket = workerSocket;
        this.taskCount = taskCount;
        this.master = master;
    }

    @Override
    public void run() {
        try (
                PrintWriter out = new PrintWriter(workerSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(workerSocket.getInputStream()));
        ) {
            // 发送任务数量给Worker
            out.println(taskCount);

            // 收集Worker的结果
            for (int i = 0; i < taskCount; i++) {
//                收集结果
                String resultStr = in.readLine();
                int result = Integer.parseInt(resultStr);
//                master收集结果
                master.addResult(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}